﻿using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;

namespace zijian666.AnyExtensions.Privates;

/// <summary>
/// 与泛型类型有关的帮助类
/// </summary>
/// <typeparam name="T"></typeparam>
internal static class GenericHelper<T>
{
    public static T[] EmptyArray { get; } = [];

    public static ReadOnlyCollection<T> ReadOnlyCollection { get; } = new(EmptyArray);

    public static IQueryable<T> EmptyQueryable { get; } = EmptyArray.AsQueryable();

    public static MethodInfo EnumerableContains { get; } = Methods.Enumerable_Contains.MakeGenericMethod(typeof(T));

    public static MethodInfo QueryableContains { get; } = Methods.Queryable_Contains.MakeGenericMethod(typeof(T));

    public static MethodInfo QueryableAny { get; } = Methods.Queryable_Any.MakeGenericMethod(typeof(T));

    public static bool CanNull { get; } = default(T) is null;

    public static Type? NullableUnderlyingType { get; } = Nullable.GetUnderlyingType(typeof(T));

    public static bool IsNullable { get; } = NullableUnderlyingType is not null;

    public static bool IsEnum { get; } = typeof(T).IsEnum;

    public static bool IsInteger { get; } = typeof(T).IsInteger();

    public static object? DefaultValue { get; } = Nullable.GetUnderlyingType(typeof(T)) is Type t ? Activator.CreateInstance(t) : default;

    public static bool TryParse(string value, out T? result)
    {
        if (TRY_PARSE_HANDLER is null)
        {
            result = default;
            return false;
        }
        return TRY_PARSE_HANDLER(value?.Trim(), out result);
    }

    private static readonly TryParseHandler<T>? TRY_PARSE_HANDLER = StringParserBuilder.Build<T>();
}